#coding=utf-8

from xml.etree.ElementTree import parse, Element

"""
    src_fp: 待翻译的原文文件
    ts_info: 中英文映射信息（字典类型）
    dst_fp: 翻译后的目标文件
"""
def translate(src_fp, ts_info, dst_fp):
    lst_no_trans = []

    """ 解析xml文件 """
    doc = parse(src_fp)
    """ 获取根节点 """
    root = doc.getroot()

    """ 获取所有context节点 """
    ctxs = root.findall("context")
    """ 遍历context节点 """
    for ctx in ctxs:
        msgs = ctx.findall("message")
        for msg in msgs:
            """ 找到原文，并设置译文 """
            src = msg.find("source")
            
            if ts_info.__contains__(src.text):
                ts_text = ts_info[src.text]
            elif ts_info.__contains__(src.text.strip()):
                ts_text = ts_info[src.text.strip()]
            else:
                lst_no_trans.append(src.text)
                continue

            for n in msg.findall("translation"):
                if n.tag=="translation":
                    n.text = "{0}".format(ts_text)
                    break

    doc.write(dst_fp, encoding="utf-8", xml_declaration=True)
    return lst_no_trans